#include <memory>
#include <string>
#include <vector>
#include <nlohmann/json.hpp>
#include "system_server.h"
#include "common_config_manager.h"
#include "hal_network.h"
#include "base_log.h"
#include "system_server_diagnosis.h"

namespace El {
namespace SystemServer {

SystemServer &SystemServer::GetInstance()
{
    static SystemServer instance;
    return instance;
}

bool SystemServer::Start()
{
    SystemServerDiagnosis::GetInstance().Start();

    InitNetwork();

    return true;
}

bool SystemServer::Stop()
{
    // 获取网络管理器实例
    auto &networkManager = Hal::NetworkManager::GetInstance();

    // 获取所有网络接口
    auto interfaces = networkManager.GetNetworkInterfaces();

    // 关闭所有网络接口
    for (const auto &iface : interfaces) {
        if (iface.type == Hal::NetIfType::ETHERNET) {
            networkManager.SetInterfaceStatus(iface.name, Hal::NetIfStatus::DOWN);
        }
    }
    return true;
}

void SystemServer::InitNetwork()
{
    // 获取网络配置
    nlohmann::json config = El::Common::ConfigManager::GetInstance().GetConfig("network");
    if (config.is_null()) {
        LOG_ERROR("Failed to get network configuration");
        return;
    }

    // 获取网络管理器实例
    auto &networkManager = Hal::NetworkManager::GetInstance();

    // 获取默认网卡名称
    std::string defaultInterface = "eth0";
    if (config.contains("defaultInterface")) {
        defaultInterface = config["defaultInterface"].get<std::string>();
    }

    // 检查接口配置是否存在
    if (!config.contains("interfaces") || !config["interfaces"].contains(defaultInterface)) {
        LOG_ERROR("Network interface configuration not found for {}", defaultInterface);
        return;
    }

    // 获取接口配置
    const auto &ifaceConfig = config["interfaces"][defaultInterface];

    // 检查接口是否启用
    if (!ifaceConfig.contains("enable") || !ifaceConfig["enable"].get<bool>()) {
        LOG_INFO("Network interface {} is disabled", defaultInterface);
        return;
    }

    // 获取所有网络接口
    auto interfaces = networkManager.GetNetworkInterfaces();

    // 查找并配置指定的网络接口
    for (const auto &iface : interfaces) {
        if (iface.name == defaultInterface) {
            // 检查接口类型
            std::string type = ifaceConfig["type"].get<std::string>();
            if (type != "ethernet" || iface.type != Hal::NetIfType::ETHERNET) {
                LOG_ERROR("Interface type mismatch for {}", defaultInterface);
                continue;
            }

            // 启用网络接口
            LOG_INFO("Enabling network interface {}", defaultInterface);
            networkManager.SetInterfaceStatus(iface.name, Hal::NetIfStatus::UP);

            // 配置网络
            bool useDhcp = ifaceConfig["dhcp"].get<bool>();
            if (useDhcp) {
                LOG_INFO("Configuring DHCP for interface {}", defaultInterface);
                if (!networkManager.ConfigureDhcp(iface.name)) {
                    LOG_ERROR("DHCP configuration failed for interface {}", iface.name);
                    // DHCP失败时使用静态IP作为后备
                    if (!networkManager.ConfigureStaticIp(iface.name, ifaceConfig["ipAddress"].get<std::string>(),
                                                          ifaceConfig["netmask"].get<std::string>(),
                                                          ifaceConfig["gateway"].get<std::string>())) {
                        LOG_ERROR("Static IP fallback configuration failed for interface {}", iface.name);
                    }
                }
            } else {
                LOG_INFO("Configuring static IP for interface {}", defaultInterface);
                if (!networkManager.ConfigureStaticIp(iface.name, ifaceConfig["ipAddress"].get<std::string>(),
                                                      ifaceConfig["netmask"].get<std::string>(),
                                                      ifaceConfig["gateway"].get<std::string>())) {
                    LOG_ERROR("Static IP configuration failed for interface {}", iface.name);
                }
            }

            // 配置DNS服务器
            std::vector<std::string> dnsServers;
            if (ifaceConfig.contains("dns1")) {
                dnsServers.push_back(ifaceConfig["dns1"].get<std::string>());
            }
            if (ifaceConfig.contains("dns2")) {
                dnsServers.push_back(ifaceConfig["dns2"].get<std::string>());
            }

            // 如果接口级DNS未配置，使用全局DNS
            if (dnsServers.empty() && config.contains("primaryDNS")) {
                dnsServers.push_back(config["primaryDNS"].get<std::string>());
                if (config.contains("secondaryDNS")) {
                    dnsServers.push_back(config["secondaryDNS"].get<std::string>());
                }
            }

            if (!dnsServers.empty()) {
                LOG_INFO("Configuring DNS servers for interface {}", defaultInterface);
                if (!networkManager.SetDnsServers(dnsServers)) {
                    LOG_ERROR("DNS server configuration failed");
                }
            }

            break;
        }
    }
}

bool SystemServer::ConfigureNetworkDhcp(const std::string &interfaceName)
{
    // 获取网络管理器实例
    auto &networkManager = Hal::NetworkManager::GetInstance();

    // 检查接口是否存在
    auto interfaces = networkManager.GetNetworkInterfaces();
    bool found = false;
    for (const auto &iface : interfaces) {
        if (iface.name == interfaceName && iface.type == Hal::NetIfType::ETHERNET) {
            found = true;
            break;
        }
    }
    if (!found) {
        LOG_ERROR("Network interface {} not found", interfaceName);
        return false;
    }

    // 启用网络接口
    networkManager.SetInterfaceStatus(interfaceName, Hal::NetIfStatus::UP);

    // 配置DHCP
    if (!networkManager.ConfigureDhcp(interfaceName)) {
        LOG_ERROR("DHCP configuration failed for interface {}", interfaceName);
        return false;
    }

    // 更新配置
    nlohmann::json config = El::Common::ConfigManager::GetInstance().GetConfig("network");
    if (!config.contains("interfaces")) {
        config["interfaces"] = nlohmann::json::object();
    }
    if (!config["interfaces"].contains(interfaceName)) {
        config["interfaces"][interfaceName] = nlohmann::json::object();
    }

    config["interfaces"][interfaceName]["enable"] = true;
    config["interfaces"][interfaceName]["type"] = "ethernet";
    config["interfaces"][interfaceName]["dhcp"] = true;

    return El::Common::ConfigManager::GetInstance().SetConfig("network", config);
}

bool SystemServer::ConfigureNetworkStatic(const std::string &interfaceName,
                                          const std::string &ipAddress,
                                          const std::string &netmask,
                                          const std::string &gateway)
{
    // 获取网络管理器实例
    auto &networkManager = Hal::NetworkManager::GetInstance();

    // 检查接口是否存在
    auto interfaces = networkManager.GetNetworkInterfaces();
    bool found = false;
    for (const auto &iface : interfaces) {
        if (iface.name == interfaceName && iface.type == Hal::NetIfType::ETHERNET) {
            found = true;
            break;
        }
    }
    if (!found) {
        LOG_ERROR("Network interface {} not found", interfaceName);
        return false;
    }

    // 启用网络接口
    networkManager.SetInterfaceStatus(interfaceName, Hal::NetIfStatus::UP);

    // 配置静态IP
    if (!networkManager.ConfigureStaticIp(interfaceName, ipAddress, netmask, gateway)) {
        LOG_ERROR("Static IP configuration failed for interface {}", interfaceName);
        return false;
    }

    // 更新配置
    nlohmann::json config = El::Common::ConfigManager::GetInstance().GetConfig("network");
    if (!config.contains("interfaces")) {
        config["interfaces"] = nlohmann::json::object();
    }
    if (!config["interfaces"].contains(interfaceName)) {
        config["interfaces"][interfaceName] = nlohmann::json::object();
    }

    config["interfaces"][interfaceName]["enable"] = true;
    config["interfaces"][interfaceName]["type"] = "ethernet";
    config["interfaces"][interfaceName]["dhcp"] = false;
    config["interfaces"][interfaceName]["ipAddress"] = ipAddress;
    config["interfaces"][interfaceName]["netmask"] = netmask;
    config["interfaces"][interfaceName]["gateway"] = gateway;
    return El::Common::ConfigManager::GetInstance().SetConfig("network", config);
}

bool SystemServer::ConfigureDnsServers(const std::string &primaryDns, const std::string &secondaryDns)
{
    // 获取网络管理器实例
    auto &networkManager = Hal::NetworkManager::GetInstance();

    // 配置DNS服务器
    std::vector<std::string> dnsServers;
    dnsServers.push_back(primaryDns);
    if (!secondaryDns.empty()) {
        dnsServers.push_back(secondaryDns);
    }

    if (!networkManager.SetDnsServers(dnsServers)) {
        LOG_ERROR("DNS server configuration failed");
        return false;
    }

    // 更新配置
    nlohmann::json config = El::Common::ConfigManager::GetInstance().GetConfig("network");
    config["primaryDNS"] = primaryDns;
    if (!secondaryDns.empty()) {
        config["secondaryDNS"] = secondaryDns;
    } else if (config.contains("secondaryDNS")) {
        config.erase("secondaryDNS");
    }

    return El::Common::ConfigManager::GetInstance().SetConfig("network", config);
}

} // namespace SystemServer
} // namespace El
